// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net.Mail;

namespace Microsoft.InformationSecurity.ISRM.TaskManagment.NotificationsService
{
    internal class EmailNotificationProcessor:INotificationProcessor
    {
        #region INotificationProcessor Members

        public void Send(Notification notificationDetails)
        {
            if (notificationDetails is EmailNotification) 
            {
                EmailNotification notification = (EmailNotification)notificationDetails;
                MailMessage message = new MailMessage();
                foreach (string to in notification.To) 
                {
                    message.To.Add(new MailAddress(to));
                }
                message.Subject = notification.Subject;
                message.Body = notification.Body;
                message.IsBodyHtml = notification.IsBodyHtml;
                message.Priority = notification.Priority;
                message.From = new MailAddress(ServiceConfiguration.FromEmailAddress);
                SmtpClient client = new SmtpClient(ServiceConfiguration.SmtpServer);
                client.UseDefaultCredentials = true;
                client.Send(message);
            }
        }

        public bool Validate(Notification notificationDetails)
        {
            if (notificationDetails != null)
            {
                if (notificationDetails.Body.Length > 0)
                    return true;
                if (notificationDetails.Subject.Length > 0 && notificationDetails.Subject.Length < 255)
                    return true;
                if (notificationDetails.To.Count > 0)
                    return true;

                foreach (string s in notificationDetails.To) 
                {
                    return !Regex.IsMatch(s, ServiceConfiguration.EmailRegularExpression);
                }

            }
            return false;
        }

        #endregion
    }
}
